#include "../includes/new_queue.h"
#include "../includes/functions.h"

int init_queue(queue_t *q, sqlite3 *DB, char *path_queue_file){
    char str[MAX_SIZE];
    char mess[MAX_SIZE];
    char SQL[MAX_SIZE];
    FILE *QUEUE;
    sqlite3_stmt *res;

    int id = 0;
    int len = 0;
    int i = 0;

    QUEUE = fopen(path_queue_file, "r");
    strcpy(SQL, "SELECT NAME FROM users WHERE ID=?;");
    while (Fgets(str, MAX_SIZE, QUEUE)){
        ParseQueueFile(str, &id, mess);

        if (sqlite3_prepare_v2(DB, SQL, -1, &res, 0) != SQLITE_OK){
            sqlite3_finalize(res);
            return 0;
        }
        else
            sqlite3_bind_int(res, 1, id);

        int ret = sqlite3_step(res);

        if (ret == SQLITE_ROW){
            strncpy(q->queue[i].name, sqlite3_column_text(res, 0), USER_SIZE);
        }
        else{
            sqlite3_finalize(res);
            return 0;
        }

        strcpy(q->queue[i].mess, mess);
        i++;
        len++;
    }

    q->len = len;
    return 1;
}


void insert_queue(queue_t *q, sock_user_link_t *sul, int fd, char *mess, char *user_name, char *path_q_file){
    FILE *Q_FILE;
    if (q->len < MAX_SIZE-1){
        strcpy(q->queue[q->len].mess, mess);
        strcpy(q->queue[q->len].name, user_name);
        q->queue[q->len].fd = fd;
    }
    else{
        perror("QUEUE IS FULL");
        exit(EXIT_FAILURE);
    }

    q->len++;
    
    Q_FILE = fopen(path_q_file, "w+");
    for (int i = 0; i < q->len; ++i){
        fprintf(Q_FILE, "%d:%s\n", sul[q->queue[i].fd].DBid, q->queue[i].mess);   
    }
    fflush(Q_FILE);
}


int is_empty_queue(const queue_t *q){
    if (q->len <= 0)
        return 1;
    else
        return 0;
}


void remove_queue(queue_t *q, sock_user_link_t *sul, int fd, char *path_q_file){
    FILE *Q_FILE;
    for (int i = 0; i < q->len; ++i){
        strcpy(q->queue[i].mess, q->queue[i+1].mess);
        strcpy(q->queue[i].name, q->queue[i+1].name);
        q->queue[i].fd = q->queue[i+1].fd;
    }

    sul[fd].DBid = 0;

    q->len--;

    Q_FILE = fopen(path_q_file, "w+");
    for (int i = 0; i < q->len; ++i){
        fprintf(Q_FILE, "%d:%s\n", sul[fd].DBid, q->queue[i].mess);   
    }
    fflush(Q_FILE);
}


int is_in_queue(queue_t *q, char *name){
    for (int i = 0; i < q->len; ++i)
        if (strcmp(name, q->queue[i].name) == 0)
            return 1;
    return 0;
}
